package com.lingxinst.farm.base.utils;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;

public class GlideUtils {

    public static void into(Activity activity, String url, final ImageView iv) {
        if (iv == null) return;
        into(activity, url, iv, 0);
    }


    public static void into(Activity activity, String url, final ImageView iv, final int defaultRes) {
        if (iv == null) return;
        if (TextUtils.isEmpty(url)) {
            if (defaultRes > 0)
                iv.setImageResource(defaultRes);
            else
                iv.setImageDrawable(null);
        } else {
            Glide.with(activity)
                    .load(url)
                    .listener(new RequestListener<Drawable>() {
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            // 图片加载失败时调用
                            if (defaultRes > 0)
                                iv.setImageResource(defaultRes);
                            else
                                iv.setImageDrawable(null);
                            return true;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            // 图片加载完成时调用
                            return false;
                        }
                    })
                    .apply(new RequestOptions().skipMemoryCache(true)
                            .diskCacheStrategy(DiskCacheStrategy.NONE))
                    .into(iv);
        }
    }

}